/**
Definition for a binary tree node. */
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
    int targetSum = 0;
    vector<int>tempList = {};
    vector<vector<int>>ans = {{}};
    void dfs(TreeNode* node, int sum){
        if(node==nullptr)
            return;
        tempList.push_back(node->val);
        if(node->left==nullptr && node->right==nullptr && sum==this->targetSum){    //说明遍历到了叶子节点
            this->ans.push_back(tempList);
        }
        if(node->left!=nullptr)
            dfs(node->left,sum+node->left->val);
        if(node->right!=nullptr)
            dfs(node->right,sum+node->right->val);
        tempList.pop_back();    //返回时弹出最后一个元素
    }
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        this->targetSum = targetSum;
        if(root!=nullptr)
            dfs(root,root->val);
        return this->ans;
    }
};